<template>
  <div>
    <nav-bar :title="title" :isShow="false"></nav-bar>
    <!-- <form action="/">
      <van-field
        style="padding-left: 23px"
        left-icon="calendar-o"
        clickable
        readonly
        label="结算时间"
        name="ym"
        :value="listQuery.ym"
        placeholder="点击选择日期"
        @click="showPicker = true"
        clearable
      />
    </form> -->
    <!-- <van-popup v-model="showPicker" position="bottom">
      <van-datetime-picker
        type="year-month"
        title="选择年月"
        v-model="currentDate"
        @confirm="onConfirm"
        @cancel="showPicker = false"
        :formatter="formatter"
      />
    </van-popup> -->

    <van-tabs v-model="active" swipeable @click="onTabChange">
      <van-tab title="商家结算" name="balance">
        <van-cell-group>
          <van-cell
            icon="shop-o"
            v-for="item in retailers"
            :key="item.id"
            :title="item.name"
            :label="item.address"
            :value="item.records"
            is-link
            center
            :to="{
              name: 'BalanceAccountList',
              params: { retailer_id: item.id },
            }"
          />
        </van-cell-group>
      </van-tab>
      <van-tab title="商家结算列表" name="history">
        <form action="/">
          <van-row type="flex" justify="space-between" align="center">
            <van-col span="16">
              <van-field
                style="padding-left: 23px"
                left-icon="calendar-o"
                clickable
                readonly
                name="calendar"
                :value="range_date"
                placeholder="点击选择日期"
                @click="showCalendar = true"
                clearable
              />
            </van-col>
            <van-col span="8">
              <van-field
                readonly
                clickable
                name="retailer"
                :value="retailer_name"
                placeholder="点击选择商家"
                @click="showPicker = true"
              />
            </van-col>
          </van-row>
        </form>
        <van-calendar
          type="range"
          v-model="showCalendar"
          :min-date="minDate"
          @confirm="onConfirm"
        />
        <van-popup v-model="showPicker" round position="bottom">
          <van-picker
            title="商家列表"
            show-toolbar
            :columns="retailers"
            value-key="name"
            @confirm="onRetailerConfirm"
            @cancel="onPickerCancel"
          />
        </van-popup>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell title="商家结算记录">
            <template>
              合计：<van-tag round type="success">{{ counts||0 }}</van-tag>
            </template>
          </van-cell>
          <van-cell-group>
            <van-cell
              icon="passed"
              v-for="item in bills"
              :key="item.id"
              :title="item.retailer_name"
              :value="item.counts"
              :label="item.bill_date"
            >
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
// import { mapGetters } from "vuex";
import NavBar from "@/components/NavBar";
import { formatDateTime } from "@/utils/datetime";
import { getWxRetailerList } from "@/api/member";
import { getWxBalanceBillHis, getWxBalanceBillStats } from "@/api/card";

export default {
  name: "BalanceAccount",
  components: {
    NavBar,
  },

  computed: {
    minDate() {
      let datetime = new Date();
      datetime = datetime.setFullYear(datetime.getFullYear() - 5);
      return new Date(datetime);
    },
  },
  data() {
    return {
      title: this.$route.meta.title,

      active: 0,
      retailers: [],
      bills: [],
      counts: 0,

      retailer_name: "",

      currentDate: new Date(),

      loading: false,
      finished: false,

      showCalendar: false,
      range_date: null,

      showPicker: false,

      listQuery: {
        page: 1,
        page_size: 10,
        retailer_id: null,
        flag:1, //后台管理
        begin_date: null,
        end_date: null,
      },
    };
  },

  created() {
    this.getRetailers();
  },

  methods: {
    getRetailers() {
      getWxRetailerList().then((res) => {
        this.retailers = res.data;
      });
    },

    onRetailerConfirm(value) {
      console.log(value);
      this.listQuery.retailer_id = value.id;
      this.retailer_name = value.name;
      this.showPicker = false;
      this.bills = [];
      this.counts = 0;
      this.listQuery.page = 1;
      this.onLoad();
    },

    onPickerCancel() {
      this.retailer_name = "";
      this.listQuery.retailer_id = null;
      this.showPicker = false;
    },

    onConfirm(date) {
      const [start, end] = date;
      this.showCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");
      this.listQuery.begin_date = begin_date;
      this.listQuery.end_date = end_date;
      this.range_date = `${begin_date} / ${end_date}`;
      this.bills = [];
      this.counts = 0;
      this.listQuery.page = 1;
      this.onLoad();
    },

    onTabChange(name) {
      if (name === "history" && this.finished == true) {
        this.range_date = null;
        this.retailer_name = "";
        this.listQuery.retailer_id = null;
        this.listQuery.begin_date = null;
        this.listQuery.end_date = null;
        this.bills = [];
        this.counts = 0;
        this.listQuery.page = 1;
        this.onLoad();
      }
    },

    onLoad() {
      this.getBalanceBillHistories();
      this.getBalanceBillStats();
    },

    getBalanceBillHistories() {
      getWxBalanceBillHis(this.listQuery)
        .then((res) => {

          if (res.data.results.length === 0) {
            this.bills = []; // 清空数组
            this.finished = true; // 停止加载
          }
          this.listQuery.page = res.data.page;
          this.bills.push(...res.data.results);
          this.loading = false;

          if (this.bills.length >= res.data.count) {
            this.finished = true; // 结束加载状态
          }
        })
        .catch(() => {
          this.loading = false;
          this.finished = true;
          this.$toast("获取数据失败！");
        });
    },

    getBalanceBillStats() {
      getWxBalanceBillStats(this.listQuery).then((res) => {
        this.counts = res.data.counts;
      });
    },
  },
};
</script>

<style  scoped>
.van-cell__title {
  flex: 5;
}
</style>